package com.maxjay.common.util.export;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class ExportUtil {
	/**
	 * 导出成Excel的工具类
	 * 
	 * @param SheetName
	 *            工作表名字
	 * @param columns
	 *            列名
	 * @param records
	 *            记录集，每个元素又是一个List，即一条记录
	 * @param os
	 *            Jun 4, 2008
	 */
	public static void exportExcel(String sheetName, List<String> columns,
			List<List<String>> records, OutputStream os) {
		WritableWorkbook wwb;
		try {
			wwb = Workbook.createWorkbook(os);

			WritableSheet ws = wwb.createSheet(sheetName, 0);
			// 表的字段名
			// 增加列名
			int columnIndex = 0;
			for (Iterator<String> it = columns.iterator(); it.hasNext(); columnIndex++) {
				String columnName = it.next();
				Label caption = new Label(columnIndex, 0, columnName);
				ws.addCell(caption);
			}
			// 遍历数据集的数据，导出数据到Excel
			int rowIndex = 1;
			Iterator<List<String>> recordsIt = records.iterator();
			while (recordsIt.hasNext()) {
				columnIndex = 0;
				Iterator<String> recordIt = recordsIt.next().iterator();
				while (recordIt.hasNext()) {
					Label caption = new Label(columnIndex, rowIndex, recordIt.next());
					ws.addCell(caption);
					columnIndex++;
				}
				rowIndex++;
			}
			wwb.write();
			wwb.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (RowsExceededException e) {
			e.printStackTrace();
		} catch (WriteException e) {
			e.printStackTrace();
		}

	}

}
